package com.zr.domain.caffeine;

import com.github.benmanes.caffeine.cache.stats.CacheStats;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.stereotype.Service;

@Service
public class CacheMonitorService {

    @Autowired
    private CacheManager cacheManager;

    public void printCacheStatistics(String cacheName) {
        CaffeineCache caffeineCache = (CaffeineCache) cacheManager.getCache(cacheName);
        if (caffeineCache != null) {
            CacheStats stats = caffeineCache.getNativeCache().stats();
            System.out.println("=== 缓存统计 [" + cacheName + "] ===");
            System.out.println("命中率: " + stats.hitRate());
            System.out.println("平均加载时间(ns): " + stats.averageLoadPenalty());
            System.out.println("总驱逐次数: " + stats.evictionCount());
            System.out.println("异常加载次数: " + stats.loadFailureCount());
        }
    }
}
